import React, { useCallback, useEffect, useRef, useState } from 'react';
import './ScreenshotSelector.css';

interface SelectionArea {
  startX: number;
  startY: number;
  endX: number;
  endY: number;
}

type DragMode = 'creating' | 'moving' | 'resizing' | null;
type ResizeHandle = 'nw' | 'ne' | 'sw' | 'se' | 'n' | 's' | 'e' | 'w' | null;

const ScreenshotSelector: React.FC = () => {
  const [isSelecting, setIsSelecting] = useState(false);
  const [selection, setSelection] = useState<SelectionArea | null>(null);
  const [screenshots, setScreenshots] = useState<string[]>([]);
  const [dragMode, setDragMode] = useState<DragMode>(null);
  const [resizeHandle, setResizeHandle] = useState<ResizeHandle>(null);
  const [dragStart, setDragStart] = useState<{ x: number; y: number } | null>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const overlayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // 获取屏幕截图
    const getScreenshots = async () => {
      try {
        // 首先尝试获取当前存储的截图数据
        const currentScreenshot = await window.electronAPI.getCurrentScreenshot();
        if (currentScreenshot) {
          setScreenshots([currentScreenshot]);
          return;
        }
        
        // 如果没有存储的截图，则重新获取
        const sources = await window.electronAPI.getSources();
        if (sources && sources.length > 0) {
          // 获取所有屏幕截图，优先使用主屏幕
          const screenSources = sources.filter(source => source.id.startsWith('screen:'));
          if (screenSources.length > 0) {
            // 使用第一个屏幕（通常是主屏幕），确保高质量
            const primaryScreen = screenSources[0];
            setScreenshots([primaryScreen.thumbnail.toDataURL()]);
          } else {
            console.error('未找到屏幕源');
            alert('无法获取屏幕截图，请重试');
            await window.electronAPI.closeScreenshotWindow();
          }
        } else {
          console.error('获取源列表为空');
          alert('无法获取屏幕截图，请重试');
          await window.electronAPI.closeScreenshotWindow();
        }
      } catch (error) {
        console.error('获取截图失败:', error);
        alert('获取截图失败，请重试');
        await window.electronAPI.closeScreenshotWindow();
      }
    };

    getScreenshots();

    // ESC 键退出 - 增强处理
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        console.log('ESC键被按下，准备关闭截图窗口');
        handleCancel();
      }
    };

    // 确保事件监听能正确工作
    document.addEventListener('keydown', handleKeyPress, true); // 使用捕获阶段
    window.addEventListener('keydown', handleKeyPress, true); // 同时监听window事件
    
    return () => {
      document.removeEventListener('keydown', handleKeyPress, true);
      window.removeEventListener('keydown', handleKeyPress, true);
    };
  }, []);

  // 组件聚焦和键盘事件处理
  useEffect(() => {
    // 确保组件获得焦点以接收键盘事件
    const container = overlayRef.current;
    if (container) {
      container.focus();
      console.log('截图选择器已获得焦点');
    }
  }, [screenshots]);

  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    const rect = overlayRef.current?.getBoundingClientRect();
    if (!rect) return;

    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    // 检查是否点击在现有选框内
    if (selection) {
      const { startX, startY, endX, endY } = selection;
      const minX = Math.min(startX, endX);
      const maxX = Math.max(startX, endX);
      const minY = Math.min(startY, endY);
      const maxY = Math.max(startY, endY);

      // 检查是否点击在调整手柄上
      const handle = getResizeHandle(mouseX, mouseY, minX, minY, maxX, maxY);
      if (handle) {
        setDragMode('resizing');
        setResizeHandle(handle);
        setDragStart({ x: mouseX, y: mouseY });
        return;
      }

      // 检查是否点击在选框内部（移动模式）
      if (mouseX >= minX && mouseX <= maxX && mouseY >= minY && mouseY <= maxY) {
        setDragMode('moving');
        setDragStart({ x: mouseX, y: mouseY });
        return;
      }
    }

    // 创建新选框
    setDragMode('creating');
    setIsSelecting(true);
    setSelection({
      startX: mouseX,
      startY: mouseY,
      endX: mouseX,
      endY: mouseY,
    });
  }, [selection]);

  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    const rect = overlayRef.current?.getBoundingClientRect();
    if (!rect) return;

    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    if (dragMode === 'creating' && isSelecting) {
      setSelection(prev => prev ? {
        ...prev,
        endX: mouseX,
        endY: mouseY,
      } : null);
    } else if (dragMode === 'moving' && selection && dragStart) {
      const deltaX = mouseX - dragStart.x;
      const deltaY = mouseY - dragStart.y;
      
      setSelection(prev => prev ? {
        startX: prev.startX + deltaX,
        startY: prev.startY + deltaY,
        endX: prev.endX + deltaX,
        endY: prev.endY + deltaY,
      } : null);
      
      setDragStart({ x: mouseX, y: mouseY });
    } else if (dragMode === 'resizing' && selection && dragStart && resizeHandle) {
      const deltaX = mouseX - dragStart.x;
      const deltaY = mouseY - dragStart.y;
      
      setSelection(prev => {
        if (!prev) return null;
        
        let { startX, startY, endX, endY } = prev;
        
        switch (resizeHandle) {
          case 'nw':
            startX += deltaX;
            startY += deltaY;
            break;
          case 'ne':
            endX += deltaX;
            startY += deltaY;
            break;
          case 'sw':
            startX += deltaX;
            endY += deltaY;
            break;
          case 'se':
            endX += deltaX;
            endY += deltaY;
            break;
          case 'n':
            startY += deltaY;
            break;
          case 's':
            endY += deltaY;
            break;
          case 'w':
            startX += deltaX;
            break;
          case 'e':
            endX += deltaX;
            break;
        }
        
        return { startX, startY, endX, endY };
      });
      
      setDragStart({ x: mouseX, y: mouseY });
    }
  }, [dragMode, isSelecting, selection, dragStart, resizeHandle]);

  const handleMouseUp = useCallback(() => {
    setIsSelecting(false);
    setDragMode(null);
    setResizeHandle(null);
    setDragStart(null);
  }, []);

  // 获取调整手柄类型
  const getResizeHandle = (mouseX: number, mouseY: number, minX: number, minY: number, maxX: number, maxY: number): ResizeHandle => {
    const handleSize = 8;
    const tolerance = 4;
    
    // 角落手柄
    if (Math.abs(mouseX - minX) <= handleSize + tolerance && Math.abs(mouseY - minY) <= handleSize + tolerance) return 'nw';
    if (Math.abs(mouseX - maxX) <= handleSize + tolerance && Math.abs(mouseY - minY) <= handleSize + tolerance) return 'ne';
    if (Math.abs(mouseX - minX) <= handleSize + tolerance && Math.abs(mouseY - maxY) <= handleSize + tolerance) return 'sw';
    if (Math.abs(mouseX - maxX) <= handleSize + tolerance && Math.abs(mouseY - maxY) <= handleSize + tolerance) return 'se';
    
    // 边缘手柄
    if (Math.abs(mouseY - minY) <= handleSize + tolerance && mouseX > minX + handleSize && mouseX < maxX - handleSize) return 'n';
    if (Math.abs(mouseY - maxY) <= handleSize + tolerance && mouseX > minX + handleSize && mouseX < maxX - handleSize) return 's';
    if (Math.abs(mouseX - minX) <= handleSize + tolerance && mouseY > minY + handleSize && mouseY < maxY - handleSize) return 'w';
    if (Math.abs(mouseX - maxX) <= handleSize + tolerance && mouseY > minY + handleSize && mouseY < maxY - handleSize) return 'e';
    
    return null;
  };

  // 获取鼠标样式
  const getCursor = (mouseX: number, mouseY: number): string => {
    if (!selection) return 'crosshair';
    
    const { startX, startY, endX, endY } = selection;
    const minX = Math.min(startX, endX);
    const maxX = Math.max(startX, endX);
    const minY = Math.min(startY, endY);
    const maxY = Math.max(startY, endY);
    
    const handle = getResizeHandle(mouseX, mouseY, minX, minY, maxX, maxY);
    
    if (handle) {
      switch (handle) {
        case 'nw':
        case 'se':
          return 'nw-resize';
        case 'ne':
        case 'sw':
          return 'ne-resize';
        case 'n':
        case 's':
          return 'ns-resize';
        case 'w':
        case 'e':
          return 'ew-resize';
      }
    }
    
    if (mouseX >= minX && mouseX <= maxX && mouseY >= minY && mouseY <= maxY) {
      return 'move';
    }
    
    return 'crosshair';
  };

  const captureSelection = async () => {
    if (!selection || !screenshots[0]) return;

    try {
      const canvas = canvasRef.current;
      if (!canvas) return;

      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      // 创建图片对象
      const img = new Image();
      img.onload = async () => {
        // 计算选择区域
        const { startX, startY, endX, endY } = selection;
        const x = Math.min(startX, endX);
        const y = Math.min(startY, endY);
        const width = Math.abs(endX - startX);
        const height = Math.abs(endY - startY);

        if (width < 10 || height < 10) {
          alert('选择区域太小，请重新选择');
          return;
        }

        // 设置画布尺寸，使用设备像素比提高清晰度
        const dpr = window.devicePixelRatio || 1;
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        
        // 缩放绘图上下文以适应设备像素比
        ctx.scale(dpr, dpr);

        // 计算缩放比例
        const scaleX = img.width / window.screen.width;
        const scaleY = img.height / window.screen.height;

        // 启用平滑处理提高图像质量
        ctx.imageSmoothingEnabled = true;
        ctx.imageSmoothingQuality = 'high';
        
        // 裁剪并绘制图像
        ctx.drawImage(
          img,
          x * scaleX,
          y * scaleY,
          width * scaleX,
          height * scaleY,
          0,
          0,
          width,
          height
        );

        // 获取高质量截图数据
        const dataURL = canvas.toDataURL('image/png', 1.0);
        
        // 同时保存截图和复制到剪贴板
        try {
          const [savedPath, clipboardSuccess] = await Promise.all([
            window.electronAPI.saveScreenshot(dataURL),
            window.electronAPI.copyToClipboard(dataURL)
          ]);
          
          // 通知主窗口截图已保存
          const filename = `screenshot-${Date.now()}.png`;
          await window.electronAPI.notifyScreenshotSaved({
            filename,
            dataURL,
            savedPath
          });
          
          const clipboardText = clipboardSuccess ? '并已复制到剪贴板' : '';
          alert(`截图已保存到: ${savedPath} ${clipboardText}`);
        } catch (error) {
          console.error('截图操作失败:', error);
          alert('截图操作失败');
        }

        // 关闭窗口
        await window.electronAPI.closeScreenshotWindow();
      };

      img.src = screenshots[0];
    } catch (error) {
      console.error('截图失败:', error);
      alert('截图失败');
    }
  };

  const handleCancel = async () => {
    console.log('取消截图，关闭窗口');
    try {
      await window.electronAPI.closeScreenshotWindow();
    } catch (error) {
      console.error('关闭截图窗口失败:', error);
      // 即使关闭失败也尝试直接关闭
      window.close();
    }
  };

  const getSelectionStyle = () => {
    if (!selection) return {};

    const { startX, startY, endX, endY } = selection;
    const x = Math.min(startX, endX);
    const y = Math.min(startY, endY);
    const width = Math.abs(endX - startX);
    const height = Math.abs(endY - startY);

    return {
      left: x,
      top: y,
      width,
      height,
    };
  };

  // 渲染调整手柄
  const renderResizeHandles = () => {
    if (!selection) return null;

    const { startX, startY, endX, endY } = selection;
    const minX = Math.min(startX, endX);
    const maxX = Math.max(startX, endX);
    const minY = Math.min(startY, endY);
    const maxY = Math.max(startY, endY);
    const width = maxX - minX;
    const height = maxY - minY;

    // 只有在选框足够大时才显示手柄
    if (width < 20 || height < 20) return null;

    const handleSize = 8;
    const halfHandle = handleSize / 2;

    const handles = [
      { type: 'nw', left: minX - halfHandle, top: minY - halfHandle },
      { type: 'ne', left: maxX - halfHandle, top: minY - halfHandle },
      { type: 'sw', left: minX - halfHandle, top: maxY - halfHandle },
      { type: 'se', left: maxX - halfHandle, top: maxY - halfHandle },
      { type: 'n', left: minX + width / 2 - halfHandle, top: minY - halfHandle },
      { type: 's', left: minX + width / 2 - halfHandle, top: maxY - halfHandle },
      { type: 'w', left: minX - halfHandle, top: minY + height / 2 - halfHandle },
      { type: 'e', left: maxX - halfHandle, top: minY + height / 2 - halfHandle },
    ];

    return handles.map(handle => (
      <div
        key={handle.type}
        className={`resize-handle resize-handle-${handle.type}`}
        style={{
          left: handle.left,
          top: handle.top,
          width: handleSize,
          height: handleSize,
        }}
      />
    ));
  };

  // 渲染选择区域信息
  const renderSelectionInfo = () => {
    if (!selection) return null;

    const { startX, startY, endX, endY } = selection;
    const width = Math.abs(endX - startX);
    const height = Math.abs(endY - startY);

    if (width < 1 || height < 1) return null;

    return (
      <div className="selection-info">
        {Math.round(width)} × {Math.round(height)}
      </div>
    );
  };

  if (screenshots.length === 0) {
    return (
      <div className="screenshot-selector">
        <div className="loading-overlay">
          <div className="loading-content">
            <div className="loading-spinner"></div>
            <p>正在获取屏幕截图...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="screenshot-selector">
      <div 
        className="screenshot-background"
        style={{ backgroundImage: `url(${screenshots[0]})` }}
      />
      
      <div
        ref={overlayRef}
        className="screenshot-overlay"
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        tabIndex={0}
        onMouseUp={handleMouseUp}
        style={{ 
          cursor: selection ? (() => {
            const rect = overlayRef.current?.getBoundingClientRect();
            if (!rect) return 'crosshair';
            // 这里需要鼠标位置，暂时使用默认光标
            return 'crosshair';
          })() : 'crosshair'
        }}
      >
        {selection && (
          <>
            <div
              className="selection-area"
              style={getSelectionStyle()}
            >
              {renderSelectionInfo()}
            </div>
            {renderResizeHandles()}
          </>
        )}
      </div>

      <canvas
        ref={canvasRef}
        style={{ display: 'none' }}
      />

      <div className="toolbar">
        <button
          className="btn-primary"
          onClick={captureSelection}
          disabled={!selection || isSelecting}
        >
          确认截图
        </button>
        <button
          className="btn-secondary"
          onClick={handleCancel}
        >
          取消
        </button>
        <div className="toolbar-tip">
          拖拽选择区域，拖拽选框移动位置，拖拽手柄调整大小，按 ESC 键取消
        </div>
      </div>
    </div>
  );
};

export default ScreenshotSelector;